//
//  FirstViewController.m
//  NewTimer
//
//  Created by Moonbeom Kwon on 12. 7. 6..
//  Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize preAlarm, slideAlarm, numberOfSlide, resultInShow;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    preAlarm.keyboardType = UIKeyboardTypeNumberPad;
    slideAlarm.keyboardType = UIKeyboardTypeNumberPad;
    numberOfSlide.keyboardType = UIKeyboardTypeNumberPad;
    
    t1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadVibrateFunc:) object:nil];
    
    alert = [[UIAlertView alloc] initWithTitle:@"**쇼 알람**"
                                       message:@"슬라이드 쇼가 종료되었습니다."
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles: nil];
    
    isEnd = NO;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


//below i made it
- (IBAction) changeSwitch: (id)sender
{
    if([preAlrView isOn] == YES) {
        [preAlarm setHidden:NO];
        NSLog(@"On");
    }
    
    else {
        [preAlarm setHidden:YES];
        [preAlarm setText:@""];
        NSLog(@"Off");
    }
}

-(IBAction) backgroundTap: (id)sender
{
    [preAlarm resignFirstResponder];
    [slideAlarm resignFirstResponder];
    [numberOfSlide resignFirstResponder];
}

-(IBAction)startShowTime:(id)sender
{
    int preAlrTime = [[preAlarm text] intValue];
    int slideAlrTime = [[slideAlarm text] intValue];
    int numOfSlide = [[numberOfSlide text] intValue];
    
    
    
    if(numOfSlide == 0) {
        UIAlertView *illigalAlert = [[UIAlertView alloc] initWithTitle:@"**슬라이드 수 오류**"
                                                               message:@"슬라이드 수가 '0'입니다."
                                                              delegate:nil
                                                     cancelButtonTitle:@"OK"
                                                     otherButtonTitles: nil];
        [illigalAlert show];
    }
    
    else if(slideAlrTime == 0) {
        UIAlertView *illigalAlert = [[UIAlertView alloc] initWithTitle:@"**알람 시간 오류**"
                                                               message:@"슬라이드 알람이 '0'입니다."
                                                              delegate:nil
                                                     cancelButtonTitle:@"OK"
                                                     otherButtonTitles: nil];
        [illigalAlert show];
    }
    
    else if(slideAlrTime <= preAlrTime) {
        UIAlertView *illigalAlert = [[UIAlertView alloc] initWithTitle:@"**알람 시간 오류**"
                                                               message:@"예비 알람이 슬라이드 알람보다 깁니다."
                                                              delegate:nil
                                                     cancelButtonTitle:@"OK"
                                                     otherButtonTitles: nil];
        [illigalAlert show];
    }
    
    else if(isEnd == NO) {
        if([t1 isExecuting] == NO){
            [t1 start];
            isEnd= YES;
        }
    }
    
    else if(isEnd == YES){
        if([t1 isExecuting] == NO){
            [self endThread];
            t1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadVibrateFunc:) object:nil];
            [t1 start];
        }
    }
}

-(IBAction) endShowTime: (id)sender
{
    if([t1 isExecuting] == YES) {
        [t1 cancel];
        [self endThread];
    }
}


- (void) endThread
{
    t1 = nil;
}

- (void)threadVibrateFunc:(NSString *)arg
{
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    /* work code */
    int preAlrTime;
    int slideAlrTime;
    int numOfSlide;
    
    int countSlide = 0;
    int countTime = 0;
    
    BOOL preAlr = NO;
    
    NSDate *standardTime;
    NSDate *nowTime;
    NSTimeInterval intervalZero = 0;
    
    
    preAlrTime = [[preAlarm text] intValue];
    slideAlrTime = [[slideAlarm text] intValue];
    numOfSlide = [[numberOfSlide text] intValue];
    
    while (countSlide < numOfSlide) {
        
        countSlide++;
        countTime = 0;
        standardTime = [[NSDate alloc] initWithTimeIntervalSinceNow:intervalZero];
        
        while (countTime <= slideAlrTime) {
            
            
            if([[NSThread currentThread] isCancelled]  == YES)
                goto endThread;
            
            //count time
            nowTime = [[NSDate alloc] initWithTimeIntervalSinceNow:intervalZero];
            
            countTime = (int) [nowTime timeIntervalSinceDate:standardTime];
            
            
            if(countTime <= slideAlrTime){
                [resultInShow performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"%d 슬라이드 : %d 초", countSlide, countTime] waitUntilDone:YES];
            }
            
            if(countTime == preAlrTime && preAlr == NO){
                preAlr = YES;
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            }
            
            
            [NSThread sleepForTimeInterval:0.1];
        }
        
        preAlr = NO;
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    
    [alert show];
    [resultInShow performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"0 슬라이드 : 0 초"] waitUntilDone:YES];
    
endThread:
    if([[NSThread currentThread] isCancelled]  == YES)
        [resultInShow performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"0 슬라이드 : 0 초"] waitUntilDone:YES];
    //[pool release];
}

@end
